package cn.cellcom.agent.struts.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.cellcom.agent.common.AgentConstant;
import cn.cellcom.agent.hql.RptAgentsHql;
import cn.cellcom.agent.pojo.TUser;
import cn.cellcom.agent.struts.form.ReporterForm;
import cn.cellcom.jar.dao.IBaseDao;
import cn.cellcom.jar.env.Env;
import cn.cellcom.jar.logon.LogonSession;
import cn.cellcom.jar.pagination.AbstractPaginationBiz;
import cn.cellcom.jar.pagination.IPaginationBiz;
import cn.cellcom.jar.util.DT;
import cn.cellcom.jar.util.LogUtil;
import cn.cellcom.jar.util.MyException;

public class ReporterDpAct extends DispatchAction {

	private IBaseDao dao;
	private IPaginationBiz pbiz;

	private Logger log = LoggerFactory.getLogger(this.getClass());

	/**
	 * 总览
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward pandect(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		long start = System.currentTimeMillis();
		ReporterForm rf = (ReporterForm) form;
		LogonSession ls = new LogonSession(req);
		TUser user = (TUser) ls.getLogonObject();
		long startTime = 0;
		long endTime = 0;
		if (rf.getDuration() == AgentConstant.DURATION.TODAY.value()) {// 今天
			startTime = DT.getToday().getTime();
		} else if (rf.getDuration() == AgentConstant.DURATION.YESTERDAY.value()) {// 昨天
			startTime = DT.getYesterday().getTime();
			endTime = DT.getToday().getTime();
		} else if (rf.getDuration() == 7) {// 近一周
			startTime = DT.getNearlyWeek().getTime();
			endTime = DT.getNextDay(DT.getToday(), 1).getTime();
		} else if (rf.getDuration() == 30) {//
			startTime = DT.getNearlyMonth().getTime();
			endTime = DT.getNextDay(DT.getToday(), 1).getTime();
		} else {
			startTime = DT.getToday().getTime();
		}
		String hql1 = "SELECT DAYOFYEAR(FROM_UNIXTIME(request_time/1000)) AS day, COUNT(DISTINCT crm) as crmCount, COUNT(id) as sessionCount"
				+ ", SUM(message_count+message_count_when_agent+agent_message_count+system_Message_Count) as messageCount"
				+ " FROM t_session where request_time >= '" + startTime + "' and end_time is not null";
		String hql2 = "SELECT HOUR(FROM_UNIXTIME(request_time/1000)) AS day, COUNT(DISTINCT crm) as crmCount, COUNT(id) as sessionCount"
				+ ", SUM(message_count+message_count_when_agent+agent_message_count+system_Message_Count) as messageCount"
				+ " FROM t_session where request_time >= '" + startTime + "' and end_time is not null";

		String hql = null;
		if (rf.getDuration() == AgentConstant.DURATION.WEEK.value() || rf.getDuration() == AgentConstant.DURATION.MONTH.value()) {
			hql = hql1;
		} else {
			hql = hql2;
		}

		if (endTime > 0) {
			hql = hql + " and request_time < '" + endTime + "'";
		}
		hql = hql + " and pid='" + user.getPid() + "' group by day order by day";
		try {
			List list = dao.myList(hql);
			/*
			 * for (int i = 0; i < list.size(); i++) { Map map = (Map)
			 * list.get(i); String dayShow = ""; Long day = (Long)
			 * map.get("day"); if (rf.getDuration() == 7 || rf.getDuration() ==
			 * 30) { dayShow =
			 * DT.getYYYYMMDD2(DT.getNextDay((int)(DT.getDayOfYear() - day))); }
			 * else { dayShow = DT.getYYYYMMDD2(DT.getNextDay(rf.getDuration())) + " " +
			 * day; } map.put("dayShow", dayShow); }
			 */
			// 补充完整的时间范围数据，例如近一周，近一个月，一天的24小时
			List<Map> mapList = new ArrayList<Map>();
			if (rf.getDuration() == AgentConstant.DURATION.TODAY.value() || rf.getDuration() == AgentConstant.DURATION.YESTERDAY.value()) {
				for (long i = 0; i < 24; i++) {
					Map map = null;
					for (int j = 0; j < list.size(); j++) {
						Map tmap = (Map) list.get(j);
						Long day = (Long) tmap.get("day");
						if (day == i) {
							map = tmap;
							break;
						}
					}
					if (map == null) {
						map = new HashMap<String, Object>();
						map.put("day", i);
						map.put("crmCount", 0);
						map.put("sessionCount", 0);
						map.put("messageCount", 0);
						mapList.add(map);
					} else {
						mapList.add(map);
					}
				}
			} else {
				Date today = DT.getToday();
				for (int i = rf.getDuration() - 1; i >= 0; i--) {// 包括今天
					Date last = DT.getNextDay(today, 0 - i);
					long dayOfYear = DT.getDayOfYear(last);
					Map map = null;
					for (int j = 0; j < list.size(); j++) {
						Map tmap = (Map) list.get(j);
						Long day = (Long) tmap.get("day");
						if (day == dayOfYear) {
							map = tmap;
							break;
						}
					}
					if (map == null) {
						map = new HashMap<String, Object>();
						map.put("day", dayOfYear);
						map.put("crmCount", 0);
						map.put("sessionCount", 0);
						map.put("messageCount", 0);
						mapList.add(map);
					} else {
						mapList.add(map);
					}
				}
			}
			// 格式化时间点的显示
			for (int i = 0; i < mapList.size(); i++) {
				Map one = mapList.get(i);
				if (rf.getDuration() == AgentConstant.DURATION.TODAY.value() || rf.getDuration() == AgentConstant.DURATION.YESTERDAY.value()) {
					Date date = DT.getNextDay(DT.getToday(), (0 - rf.getDuration()));
					one.put("day", DT.getYYYYMMDD2(date) + " " + one.get("day"));
				} else {
					Date date = DT.getDateOfYear(((Long) one.get("day")).intValue());
					one.put("day", DT.getYYYYMMDD2(date));
				}
			}

			req.setAttribute(Env.DATA_NAME, mapList);
		} catch (MyException e) {
			return LogUtil.e(this.clazz, "操作出现错误", e, mapping, req);
		} finally {
			log.info("[{}] get Report pandect cost[{}]", user.getUsername(), String.valueOf((System.currentTimeMillis() - start)));
		}
		return mapping.findForward("pandect");
	}

	/**
	 * 坐席工作量统计
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward agents(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		form = (ActionForm) AbstractPaginationBiz.getPaginationActionForm(req, form);
		try {
			RptAgentsHql hql = new RptAgentsHql();
			String setCountHql = "select count(1) from (" + hql.getHql(req, form) + ") as temp";
			pbiz.setCountHql(setCountHql);
			List list = pbiz.pagination(mapping, form, req, hql).getDataResult();
			req.setAttribute(Env.DATA_NAME, list);
		} catch (MyException e) {
			return LogUtil.e(this.clazz, "操作出现错误", e, mapping, req);
		}
		return mapping.findForward("agents");
	}

	public void setPbiz(IPaginationBiz pbiz) {
		this.pbiz = pbiz;
	}

	public void setDao(IBaseDao dao) {
		this.dao = dao;
	}

}
